package Servlet;

import db.DBUtil;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.HashMap;

public class LoginServlet extends HttpServlet {
    public LoginServlet() {
        super();
    }


    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("UTF-8");
        String account = request.getParameter("account"); // 从 request 中获取名为 account 的参数的值
        String password = request.getParameter("password"); // 从 request 中获取名为 password 的参数的值

        String resCode = "";

        try {
            Connection connect = DBUtil.getConnect();
            Statement statement = connect.createStatement(); // Statement可以理解为数据库操作实例，对数据库的所有操作都通过它来实现
            ResultSet result;

            String sqlQuery = "select password from user_account where username='" + account + "'";

            result = statement.executeQuery(sqlQuery); // 先查询同样的账号（比如手机号）是否存在
            if(!result.next()){ // 不存在
                resCode = "-2";
            } else { // 存在
                String password_in_server = result.getString("password");
                if(password.compareTo(password_in_server) == 0){
                    resCode = "0";//正确
                } else {
                    resCode = "-1";//错误
                }
            }

        } catch (SQLException e) {
            e.printStackTrace();
        }

        HashMap<String, String> map = new HashMap<>();
        map.put("Code", resCode);

        response.setContentType("text/html;charset=utf-8"); // 设置响应报文的编码格式
        PrintWriter pw = response.getWriter(); // 获取 response 的输出流
        pw.println(map.toString()); // 通过输出流把业务逻辑的结果输出
        pw.flush();
    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }
}
